package com.hyh.media;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;

import com.hyh.speex.Speex;

/**
 * Created by Administrator on 2019/1/27.
 */

public class AudioTrackUtil {

    private AudioTrack audioTrack;
    private Speex speex;
    private boolean playFlag = false;
    private static AudioTrackUtil audioTrackUtil;

    private AudioTrackUtil(){
        speex = Speex.getInstance();
        audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,8000, AudioFormat.CHANNEL_OUT_MONO,AudioFormat.ENCODING_PCM_16BIT,speex.getFrameSize(),AudioTrack.MODE_STREAM);
    }

    public static synchronized AudioTrackUtil getInstance(){
        if(audioTrackUtil==null){
            audioTrackUtil = new AudioTrackUtil();
        }
        return audioTrackUtil;
    }

    public void startPlay(){
        if(!playFlag){
            playFlag = true;
            audioTrack.play();
        }
    }

    public void stopPlay(){
        if(playFlag){
            playFlag = false;
            audioTrack.stop();
        }
    }

    public void write(byte buf[]){
        if(playFlag){
            short shortBuf[] = new short[speex.getFrameSize()];
            int len=speex.decode(buf,shortBuf,buf.length);
            speex.playback(shortBuf);
            audioTrack.write(shortBuf,0,len);
        }
    }
}
